import os
import yaml
from src.common.logger import getLogger

logger = getLogger()

class Config:

    def __init__(self, file_name: str = "application.yml"):
        self.config_path = self.parse_config_path(file_name)
        self.environment = os.getenv("FLASK_ENV", "development")
        self._config = self._load_config()

    def parse_config_path(self, file_name):
        abspath = os.path.dirname(os.path.abspath(__file__))
        return abspath.replace("common", "resources") + "\\" + file_name

    def _load_config(self):
        logger.info(f"Config _load_config file_path: {self.config_path}")
        if not os.path.exists(self.config_path):
            raise FileNotFoundError("未找到配置文件")

        with open(self.config_path, 'r', encoding = "utf-8") as file:
            config_str = file.read()
            config_str = self._replace_env_vars(config_str)
            config = yaml.safe_load(config_str)
        logger.info(f"Config _load_config config: {config}")
        return config

    def _replace_env_vars(self, config_str: str) -> str:
        """替换配置中的环境变量占位符"""
        import re
        def replace_match(match):
            env_var = match.group(1)
            return os.getenv(env_var, '')
        return re.sub(r'\$\{([^}]+)\}', replace_match, config_str)

    def get_database_uri(self) -> str:
        """构建数据库连接URI"""
        db_config = self._config['database']
        return (
            f"{db_config['driver']}://"
            f"{db_config['username']}:{db_config['password']}@"
            f"{db_config['host']}:{db_config['port']}/"
            f"{db_config['dbname']}"
        )

    def get_flask_config(self):
        """获取Flask配置字典"""
        flask_config = {
            'SQLALCHEMY_DATABASE_URI': self.get_database_uri(),
            'ENV': self.environment,
        }

        # 添加其他配置
        for section in ['sqlalchemy', 'app']:
            section_config = self._config.get(section, {})
            for key, value in section_config.items():
                flask_config[key] = value
        return flask_config

    def parse_config_key(self, keys):
        configs = {}
        for key in keys:
            section = self._config.get(key, {})
            for key, value in section.items():
                configs[key] = value
        return configs

config = Config()
